package com.hente.common;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
 
public class BaiduAPIConverter {
 
	private ScriptEngineManager sem;
	private ScriptEngine se ;
	private static BaiduAPIConverter instance = new BaiduAPIConverter();
	private BaiduAPIConverter(){
	    sem = new ScriptEngineManager();  
        se = sem.getEngineByName("javascript");  
	};
	
	public String[] convertLL2MC(double lng,double lat,String realPath){
		Reader reader = null;
		String[] point = new String[2];
		try {
			reader = new FileReader(realPath + "wap/js/suanfa.js");
			se.eval(reader);
	    	se.eval("var point = (convertLL2MC({'lng':" + lng + ",'lat':" + lat + "}));");  
	    	point[0] = (String)se.eval("point.x + ''");
	    	point[1] = (String)se.eval("point.y + ''");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ScriptException e) {
			e.printStackTrace();
		}finally {
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    	
		return point;
	}
	
    public String postUrl(String postUrl) throws IOException {
    	System.out.println(postUrl);
        URL url = new URL(postUrl);
        URLConnection connection = url.openConnection();
        /**
         * 然后把连接设为输出模式。URLConnection通常作为输入来使用，比如下载一个Web页。
         * 通过把URLConnection设为输出，你可以把数据向你个Web页传送。下面是如何做：
         */
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        // remember to clean up
        out.flush();
        out.close();
        // 一旦发送成功，用以下方法就可以得到服务器的回应：
        String sCurrentLine = "";
        StringBuffer sTotalString = new StringBuffer();
        InputStream l_urlStream = connection.getInputStream();
        BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream));
        while ((sCurrentLine = l_reader.readLine()) != null) {
            if (!sCurrentLine.equals(""))
            	sTotalString.append(sCurrentLine);
        }
        System.out.println(sTotalString);
        return sTotalString.toString();
    }

	public static BaiduAPIConverter getInstance() {
		return instance;
	}
}
